package com.company.genealogy.web.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.genealogy.common.constant.ApiCodeEnum;
import com.company.genealogy.common.result.ApiResponse;

import com.company.genealogy.common.util.JwtUtil;
import com.company.genealogy.web.entity.FamilyNews;
import com.company.genealogy.web.entity.Clan;
import com.company.genealogy.web.entity.User;
import com.company.genealogy.web.service.ClanService;
import com.company.genealogy.web.service.FamilyNewsService;
import com.company.genealogy.web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.HashMap;

/**
 * @author chenzhixiang
 */
@RestController
@RequestMapping("/api/v1/family-news")
public class FamilyNewsController {
    @Autowired
    private FamilyNewsService familyNewsService;
    @Autowired
    private ClanService clanService;
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;

    // 分页查询动态列表
    @GetMapping
    public ApiResponse<IPage<FamilyNews>> list(@RequestParam(defaultValue = "1") int page,
                                               @RequestParam(defaultValue = "10") int size,
                                               @RequestParam(required = false) Long clanId,
                                               @RequestParam(required = false) String type) {
        Page<FamilyNews> p = new Page<>(page, size);
        IPage<FamilyNews> result = familyNewsService.lambdaQuery()
                .eq(clanId != null, FamilyNews::getClanId, clanId)
                .eq(type != null && !type.isEmpty(), FamilyNews::getType, type)
                .orderByDesc(FamilyNews::getCreatedAt)
                .page(p);
        // 批量填充家族名称，避免N+1查询
        Set<Long> clanIds = result.getRecords().stream()
                .map(FamilyNews::getClanId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        Map<Long, String> clanIdNameMap;
        if (!clanIds.isEmpty()) {
            List<Clan> clans = clanService.listByIds(clanIds);
            clanIdNameMap = clans.stream().collect(Collectors.toMap(Clan::getId, Clan::getName));
        } else {
            clanIdNameMap = java.util.Collections.emptyMap();
        }
        result.getRecords().forEach(news -> {
            if (news.getClanId() != null) {
                news.setClanName(clanIdNameMap.get(news.getClanId()));
            }
        });
        return ApiResponse.success();
    }

    // 动态详情
    @GetMapping("/{id}")
    public ApiResponse<FamilyNews> detail(@PathVariable Long id) {
        FamilyNews news = familyNewsService.getById(id);
        if (news != null) {
            // 填充家族名称
            if (news.getClanId() != null) {
                Clan clan = clanService.getById(news.getClanId());
                if (clan != null) {
                    news.setClanName(clan.getName());
                }
            }
            // 填充作者名称
            if (news.getAuthorId() != null) {
                User user = userService.getById(news.getAuthorId());
                if (user != null) {
                    news.setAuthorName(user.getNickname() != null ? user.getNickname() : user.getUsername());
                }
            }
        }
        return ApiResponse.success(news);
    }

    // 新增动态
    @PostMapping
    public ApiResponse<FamilyNews> create(@RequestBody FamilyNews news) {
        // 获取当前登录用户（假设有工具类或上下文获取当前用户）
        User user = userService.getById(news.getAuthorId());
        if (user != null) {
            news.setAuthorName(user.getNickname() != null ? user.getNickname() : user.getUsername());
        }
        familyNewsService.save(news);
        return ApiResponse.success(news);
    }

    // 更新动态
    @PutMapping("/{id}")
    public ApiResponse<Void> update(@PathVariable Long id, @RequestBody FamilyNews news) {
        news.setId(id);
        // 获取当前登录用户（假设有工具类或上下文获取当前用户）
        User user = userService.getById(news.getAuthorId());
        if (user != null) {
            news.setAuthorName(user.getNickname() != null ? user.getNickname() : user.getUsername());
        }
        familyNewsService.updateById(news);
        return ApiResponse.success();
    }

    // 删除动态
    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Long id) {
        familyNewsService.removeById(id);
        return ApiResponse.success();
    }

    @PostMapping("/{id}/like")
    public ApiResponse<Void> likeFamilyNews(@PathVariable Long id, @RequestHeader("Authorization") String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        Long userId = jwtUtil.getUserIdFromToken(token);
        if (userId == null) {
            return ApiResponse.fail("未登录");
        }
        if (familyNewsService.hasUserLiked(id, userId)) {
            return ApiResponse.fail("已点赞");
        }
        familyNewsService.likeNews(id, userId);
        return ApiResponse.success(ApiCodeEnum.LIKE_SUCCESS);
    }
    
    @DeleteMapping("/{id}/like")
    public ApiResponse<Void> unlikeFamilyNews(@PathVariable Long id, @RequestHeader("Authorization") String token) {
        Long userId = jwtUtil.getUserIdFromToken(token);
        if (userId == null) {
            return ApiResponse.fail(ApiCodeEnum.UNAUTHORIZED);
        }
        if (!familyNewsService.hasUserLiked(id, userId)) {
            return ApiResponse.fail("未点赞");
        }
        familyNewsService.unlikeNews(id, userId);
        return ApiResponse.success();
    }
    
    @GetMapping("/likes")
    public ApiResponse<Object> getNewsLikes(@RequestParam("newsIds") List<Long> newsIds) {
        try {
            List<Map<String, Object>> likesData = familyNewsService.getNewsLikes(newsIds);
            return ApiResponse.success(likesData);
        } catch (Exception e) {
            return ApiResponse.fail("获取点赞详情失败: " + e.getMessage());
        }
    }
    
    /**
     * 增加浏览量
     */
    @PostMapping("/{id}/view")
    public ApiResponse<Object> increaseViewCount(@PathVariable Long id) {
        try {
            FamilyNews news = familyNewsService.getById(id);
            if (news == null) {
                return ApiResponse.fail("动态不存在");
            }
            
            // 增加浏览量
            Integer viewCount = news.getViewCount();
            if (viewCount == null) {
                viewCount = 0;
            }
            viewCount++;
            news.setViewCount(viewCount);
            
            // 更新数据库
            familyNewsService.updateById(news);
            
            // 返回最新浏览量
            Map<String, Object> result = new HashMap<>();
            result.put("view_count", viewCount);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.fail("增加浏览量失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户点赞状态
     * 返回当前用户对指定动态列表的点赞状态
     */
    @GetMapping("/user-likes")
    public ApiResponse<Object> getUserLikes(@RequestParam("newsIds") List<Long> newsIds, @RequestHeader("Authorization") String token) {
        try {
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                return ApiResponse.fail("未登录");
            }
            
            // 获取用户对这些动态的点赞状态
            List<Map<String, Object>> userLikes = familyNewsService.getUserLikes(userId, newsIds);
            return ApiResponse.success(userLikes);
        } catch (Exception e) {
            return ApiResponse.fail("获取点赞状态失败: " + e.getMessage());
        }
    }
} 